package cn.tedu.bs.admin.util;

import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.UUID;

public class ServiceUtil {
    /**
     * 保存上传的文件到服务器
     *
     * @param file
     * @return
     */
    public static String saveFileToStorage(MultipartFile file) throws IOException {
        String server="http://176.61.4.48:9181/upload";
        String boundary = Long.toHexString(System.currentTimeMillis());
        String CRLF = "\r\n";

        URL url = new URL(server);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

        // Generate a unique filename using UUID
        String originalFilename = file.getOriginalFilename();
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String newFilename = UUID.randomUUID().toString() + extension;

        try (
                OutputStream output = connection.getOutputStream();
                PrintWriter writer = new PrintWriter(new OutputStreamWriter(output, "UTF-8"), true);
        ) {
            writer.append("--" + boundary).append(CRLF);
            writer.append("Content-Disposition: form-data; name=\"image\"; filename=\"" + newFilename + "\"").append(CRLF);
            writer.append("Content-Type: " + file.getContentType()).append(CRLF);
            writer.append("Content-Transfer-Encoding: binary").append(CRLF);
            writer.append(CRLF).flush();

            byte[] bytes = file.getBytes();
            output.write(bytes, 0, bytes.length);
            output.flush();

            writer.append(CRLF).flush();
            writer.append("--" + boundary + "--").append(CRLF).flush();
        }

        int responseCode = connection.getResponseCode();
        System.out.println(responseCode); // should print 200
        return "/"+newFilename;
    }
}
